// 简单的i18n备用解决方案，避免CSP问题
import enUS from '../i18n/locales/en-US'
import zhCN from '../i18n/locales/zh-CN'

type MessageObject = Record<string, any>

const messages: Record<string, MessageObject> = {
  'zh-CN': zhCN,
  'en-US': enUS
}

// 获取当前语言
export const getCurrentLang = (): string => {
  return localStorage.getItem('language') || 'zh-CN'
}

// 设置语言
export const setLang = (lang: string) => {
  localStorage.setItem('language', lang)
  // 触发自定义事件通知组件更新
  window.dispatchEvent(new CustomEvent('language-changed', { detail: lang }))
}

// 获取嵌套对象值的工具函数
const getNestedValue = (obj: any, path: string): any => {
  return path.split('.').reduce((current, key) => {
    return current && current[key] !== undefined ? current[key] : null
  }, obj)
}

// 翻译函数
export const t = (key: string, params?: Record<string, any>): string => {
  const currentLang = getCurrentLang()
  const currentMessages = messages[currentLang] || messages['zh-CN']
  
  let value = getNestedValue(currentMessages, key)
  
  // 如果当前语言没有找到，尝试中文
  if (value === null && currentLang !== 'zh-CN') {
    value = getNestedValue(messages['zh-CN'], key)
  }
  
  // 如果还是没找到，返回key
  if (value === null) {
    console.warn(`Translation key not found: ${key}`)
    return key
  }
  
  // 简单的参数替换
  if (params && typeof value === 'string') {
    return value.replace(/\{(\w+)\}/g, (match, paramKey) => {
      return params[paramKey] !== undefined ? String(params[paramKey]) : match
    })
  }
  
  return String(value)
}

// 创建一个响应式的翻译hook
export const useTranslation = () => {
  const translate = (key: string, params?: Record<string, any>) => {
    return t(key, params)
  }
  
  return { t: translate }
} 